const StrategyManager = require('./managers/StrategyManager')
const { PositionManager } = require('./managers/PositionManager')
const MacdLongUpStrategy = require('./strategies/trend/MacdLongUpStrategy')
const MarketResonanceStrategy = require('./strategies/resonance/MarketResonanceStrategy')

/**
 * 重构后的BuySellMachine
 *
 * 集成策略管理器、仓位管理器等组件
 * 提供向后兼容的接口，同时使用新的架构
 */
class BuySellMachineV2 {
  constructor (config) {
    // 保持原有构造函数参数兼容性
    this.config = config
    this.btbItem = config.btbItem
    this.realBuySell = config.realBuySell || false
    this.preFind = config.preFind || false

    // 初始化新的组件
    this.strategyManager = new StrategyManager({
      maxConcurrentStrategies: 10,
      executionTimeout: 30000,
      enableStatistics: true,
      logLevel: 'info'
    })

    this.positionManager = new PositionManager({
      basePositionSize: 0.1,
      maxPositionSize: 0.4,
      maxTotalPosition: 0.8
    })

    // 注册策略
    this.initializeStrategies()

    // 设置策略链
    this.setupStrategyChains()

    // 兼容性属性（保持原有接口）
    this.buy = false
    this.sell = false
    this.pingDuo = false
    this.pingKong = false
    this.buyReason = ''
    this.sellReason = ''
    this.pingDuoReason = ''
    this.pingKongReason = ''
    this.buySellPriority = 0
    this.trackList = []

    // 执行结果
    this.lastExecutionResult = null
    this.lastPositionCalculation = null

    this.setupEventListeners()
  }

  /**
   * 初始化策略
   */
  initializeStrategies () {
    // 注册MACD长期上涨策略
    const macdLongUpStrategy = new MacdLongUpStrategy({
      priority: 80,
      parameters: {
        minMacdUpDays: 22,
        minEmaUpDays: 18,
        kdjThreshold: 0
      }
    })

    this.strategyManager.registerStrategy(macdLongUpStrategy, {
      group: 'trend',
      autoStart: true
    })

    // 注册市场共振策略
    const marketResonanceStrategy = new MarketResonanceStrategy({
      priority: 90,
      parameters: {
        minResonanceStrength: 0.7,
        minAlignedTimeframes: 2,
        minAlignedIndicators: 2
      }
    })

    this.strategyManager.registerStrategy(marketResonanceStrategy, {
      group: 'resonance',
      autoStart: true
    })
  }

  /**
   * 设置策略链
   */
  setupStrategyChains () {
    // 主要交易链
    this.strategyManager.setStrategyChain('main_trading', [
      'market_resonance',
      'macd_long_up'
    ], {
      parallel: false,
      stopOnFirst: false,
      timeout: 30000
    })

    // 高优先级链
    this.strategyManager.setStrategyChain('high_priority', [
      'market_resonance'
    ], {
      parallel: true,
      stopOnFirst: true,
      timeout: 15000
    })
  }

  /**
   * 设置事件监听
   */
  setupEventListeners () {
    this.strategyManager.on('strategySignalGenerated', (data) => {
      console.log(`策略${data.strategy}生成信号:`, data.signal.reason)
    })

    this.strategyManager.on('executionCompleted', (data) => {
      console.log(`策略链${data.chainName}执行完成，耗时${data.executionTime}ms`)
    })

    this.strategyManager.on('conflictResolved', (data) => {
      console.log(`解决策略冲突: ${data.conflictType}, 选择策略: ${data.resolvedStrategy}`)
    })

    this.positionManager.on('positionCalculated', (data) => {
      console.log(`仓位计算完成: ${data.signal}, 仓位大小: ${(data.position.size * 100).toFixed(2)}%`)
    })
  }

  /**
   * 执行策略分析（主要入口方法）
   * 保持与原有BuySellMachine兼容的接口
   */
  async execute () {
    try {
      // 准备市场数据和分析数据
      const marketData = this.prepareMarketData()
      const analysisData = this.prepareAnalysisData()

      // 执行策略链
      const signal = await this.strategyManager.executeStrategies(
        'main_trading',
        marketData,
        analysisData
      )

      if (signal) {
        // 计算仓位
        const accountInfo = this.prepareAccountInfo()
        const marketConditions = this.prepareMarketConditions(marketData)

        const positionInfo = this.positionManager.calculatePosition(
          signal,
          marketConditions,
          accountInfo
        )

        // 更新兼容性属性
        this.updateCompatibilityProperties(signal, positionInfo)

        // 保存执行结果
        this.lastExecutionResult = signal
        this.lastPositionCalculation = positionInfo

        return {
          signal,
          position: positionInfo,
          success: true
        }
      }

      // 没有信号时重置状态
      this.resetSignalState()

      return {
        signal: null,
        position: null,
        success: true
      }
    } catch (error) {
      console.error('策略执行失败:', error.message)
      this.resetSignalState()

      return {
        signal: null,
        position: null,
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 准备市场数据
   */
  prepareMarketData () {
    return {
      // 从原有的marketInfo获取数据
      attack15m: this.marketInfo?.attack15m || false,
      crash15m: this.marketInfo?.crash15m || false,
      kdj15mGood: this.marketInfo?.kdj15mGood || false,
      kdj15mBad: this.marketInfo?.kdj15mBad || false,
      macd15mGood: this.marketInfo?.macd15mGood || false,
      macd15mBad: this.marketInfo?.macd15mBad || false,
      ema15mGood: this.marketInfo?.ema15mGood || false,
      ema15mBad: this.marketInfo?.ema15mBad || false,
      kdj1hGood: this.marketInfo?.kdj1hGood || false,
      kdj1hBad: this.marketInfo?.kdj1hBad || false,
      macd1hGood: this.marketInfo?.macd1hGood || false,
      macd1hBad: this.marketInfo?.macd1hBad || false,
      kdj4hGood: this.marketInfo?.kdj4hGood || false,
      kdj4hBad: this.marketInfo?.kdj4hBad || false,
      macd4hGood: this.marketInfo?.macd4hGood || false,
      macd4hBad: this.marketInfo?.macd4hBad || false,
      isMarketChaos: this.marketFlagInfo?.isMarketChaos || false,
      volatility: this.calculateVolatility(),
      liquidity: this.calculateLiquidity(),
      strategy: this.strategy || '1'
    }
  }

  /**
   * 准备分析数据
   */
  prepareAnalysisData () {
    return {
      analysisInfo15m: this.analysisInfo15m || {},
      analysisInfo1h: this.analysisInfo1h || {},
      analysisInfo4h: this.analysisInfo4h || {},
      analysisInfo1d: this.analysisInfo1d || {},
      marketFlagInfo: this.marketFlagInfo || {},
      indexFlagInfo: this.indexFlagInfo || {},
      strategy: this.strategy || '1'
    }
  }

  /**
   * 准备账户信息
   */
  prepareAccountInfo () {
    return {
      totalBalance: this.futuresAccount?.totalWalletBalance || 10000,
      availableBalance: this.futuresAccount?.availableBalance || 10000,
      totalPosition: this.calculateCurrentTotalPosition(),
      unrealizedPnl: this.futuresAccount?.totalUnrealizedProfit || 0,
      maxDrawdown: this.calculateMaxDrawdown()
    }
  }

  /**
   * 准备市场条件
   */
  prepareMarketConditions (marketData) {
    return {
      volatility: marketData.volatility,
      liquidity: marketData.liquidity,
      isMarketChaos: marketData.isMarketChaos,
      trendConsistency: this.assessTrendConsistency(),
      trendClarity: this.assessTrendClarity()
    }
  }

  /**
   * 更新兼容性属性
   */
  updateCompatibilityProperties (signal, positionInfo) {
    // 重置所有状态
    this.resetSignalState()

    // 根据信号类型设置相应属性
    switch (signal.type) {
      case 'BUY':
        this.buy = true
        this.buyReason = signal.reason
        this.buyRate = positionInfo.size
        break
      case 'SELL':
        this.sell = true
        this.sellReason = signal.reason
        this.sellRate = positionInfo.size
        break
      case 'PING_DUO':
        this.pingDuo = true
        this.pingDuoReason = signal.reason
        this.pingDuoRate = positionInfo.size
        break
      case 'PING_KONG':
        this.pingKong = true
        this.pingKongReason = signal.reason
        this.pingKongRate = positionInfo.size
        break
    }

    // 设置优先级
    this.buySellPriority = this.calculateCompatibilityPriority(signal, positionInfo)

    // 添加到跟踪列表
    this.trackList.push({
      name: signal.reason,
      type: `set${signal.type}`,
      timestamp: Date.now(),
      confidence: signal.confidence,
      positionSize: positionInfo.size
    })
  }

  /**
   * 重置信号状态
   */
  resetSignalState () {
    this.buy = false
    this.sell = false
    this.pingDuo = false
    this.pingKong = false
    this.buyReason = ''
    this.sellReason = ''
    this.pingDuoReason = ''
    this.pingKongReason = ''
    this.buyRate = 0
    this.sellRate = 0
    this.pingDuoRate = 0
    this.pingKongRate = 0
    this.buySellPriority = 0
  }

  /**
   * 计算兼容性优先级
   */
  calculateCompatibilityPriority (signal, positionInfo) {
    let priority = 0

    // 基于仓位大小
    if (positionInfo.size >= 0.3) priority = 10
    else if (positionInfo.size >= 0.2) priority = 9
    else if (positionInfo.size >= 0.1) priority = 3
    else if (signal) priority = 1

    // 基于置信度调整
    if (signal.confidence >= 0.8) priority += 2
    else if (signal.confidence >= 0.6) priority += 1

    return priority
  }

  /**
   * 计算当前总仓位
   */
  calculateCurrentTotalPosition () {
    // 这里应该从实际的持仓信息计算
    // 暂时返回0作为示例
    return 0
  }

  /**
   * 计算最大回撤
   */
  calculateMaxDrawdown () {
    // 这里应该基于历史数据计算实际回撤
    return 0
  }

  /**
   * 计算波动率
   */
  calculateVolatility () {
    // 基于价格数据计算波动率
    return 0.03 // 默认3%
  }

  /**
   * 计算流动性
   */
  calculateLiquidity () {
    return 1.0 // 默认完全流动
  }

  /**
   * 评估趋势一致性
   */
  assessTrendConsistency () {
    // 检查多时间框架趋势一致性
    return true // 简化实现
  }

  /**
   * 评估趋势清晰度
   */
  assessTrendClarity () {
    if (this.marketFlagInfo?.ifMarket15mAllGood || this.marketFlagInfo?.ifMarket15mAllBad) {
      return 'HIGH'
    }
    return 'MEDIUM'
  }

  /**
   * 获取预信息（兼容性方法）
   */
  getPreInfo () {
    return {
      buy: this.buy,
      sell: this.sell,
      addPool: this.addPool || false,
      buySellPriority: this.buySellPriority,
      lastSignal: this.lastExecutionResult,
      lastPosition: this.lastPositionCalculation
    }
  }

  /**
   * 获取统计信息
   */
  getStatistics () {
    return {
      strategyManager: this.strategyManager.getExecutionStatistics(),
      positionManager: this.positionManager.getStatistics(),
      strategies: this.strategyManager.getStrategies().map(s => ({
        name: s.name,
        stats: this.strategyManager.getStrategyStatistics(s.name)
      }))
    }
  }

  /**
   * 获取买卖优先级（兼容性方法）
   */
  getBuySellPriority () {
    return this.buySellPriority
  }

  /**
   * 设置策略（兼容性方法）
   */
  setStrategy (strategy, reason) {
    this.strategy = strategy
    this.strategyResult = reason
  }

  /**
   * 销毁实例
   */
  destroy () {
    if (this.strategyManager) {
      this.strategyManager.destroy()
    }

    // 清理其他资源
    this.trackList = []
    this.lastExecutionResult = null
    this.lastPositionCalculation = null
  }
}

module.exports = BuySellMachineV2
